package com.ltmonitor.service;

import org.apache.log4j.Logger;
import org.apache.mina.core.future.WriteFuture;
import org.apache.mina.core.service.IoAcceptor;
import org.apache.mina.core.service.IoHandler;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.core.session.IoSessionConfig;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.servlet.ServletOutputStream;
import java.io.*;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;

@Service("videoStreamService")
public class VideoStreamService implements IVideoStreamService {
    protected Logger logger = Logger.getLogger(getClass());

    private List<byte[]> packets = new ArrayList<byte[]>();

    private int port;

    @Override
    public List<byte[]> getPackets()
    {
        return packets;
    }

    public void start() {
        try {
            dataAccepter = new NioSocketAcceptor();

            dataAccepter.getFilterChain().addLast("codec",
                    new ProtocolCodecFilter(new JT808MessageCodecFactory()));

            IoSessionConfig config = dataAccepter.getSessionConfig();

            config.setReadBufferSize(4096);
            config.setWriteTimeout(40000);
            config.setWriterIdleTime(400000);

            config.setIdleTime(IdleStatus.BOTH_IDLE, 70000);

            dataAccepter.setHandler((IoHandler)this.jt808ServerHandler);

            dataAccepter.bind(new InetSocketAddress(port));
        } catch (Exception e) {
            logger.error("808服务器启动失败:" + e.getMessage(), e);
            e.printStackTrace();
        }
    }


    public IoAcceptor dataAccepter = null;
    @Autowired
    private IJT808ServerHandler jt808ServerHandler;
    public void Stop()
    {
        if (null!=dataAccepter) {
            dataAccepter.unbind();
            dataAccepter.getFilterChain().clear();
            dataAccepter.dispose();
            dataAccepter = null;
        }
    }
    @Override
    public void init()
    {
        File file = new File("c:/rtpadas.txt" );

        InputStream in = null;
        ServletOutputStream out = null;
        try {
            in = new FileInputStream(file);
            InputStreamReader read = new InputStreamReader(
                    in, "UTF-8");
            BufferedReader reader = new BufferedReader(read);
            String line;
            try {
                //循环，每次读一行
                while ((line = reader.readLine()) != null) {
                    byte[] b = HexString2Bytes(line);
                    packets.add(b);
                    Thread.sleep(5);
                }
                reader.close();
                read.close();
            } catch (Exception e) {
                logger.error(e.getMessage(),e);
            }

        } catch (FileNotFoundException e) {
            System.out.println("文件读取失败,文件不存在");
            logger.error(e.getMessage(),e);
        } catch (IOException e) {
            System.out.println("文件流输出异常");
            logger.error(e.getMessage(),e);
        } finally {
            try {
                if(in != null)
                    in.close();
                if(out != null)
                    out.close();
            } catch (IOException e) {
                System.out.println("文件流关闭异常");
                logger.error(e.getMessage(),e);
            }
        }
    }
    public static byte[] HexString2Bytes(String hexstr) {
        byte[] b = new byte[hexstr.length() / 2];
        int j = 0;

        for (int i = 0; i < b.length; i++) {
            char c0 = hexstr.charAt(j++);
            char c1 = hexstr.charAt(j++);

            b[i] = ((byte) (parse(c0) << 4 | parse(c1)));
            //int start = i * 2;
            //int c = Integer.parseInt(hexstr.substring(start, start + 2));
            //b[i] = (byte)c;
        }

        return b;
    }

    private static int parse(char c) {
        if (c >= 'a') {
            return c - 'a' + 10 & 0xF;
        }

        if (c >= 'A') {
            return c - 'A' + 10 & 0xF;
        }

        return c - '0' & 0xF;
    }
}
